package utils

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 定义响应状态码和消息常量
const (
	Success           = http.StatusOK
	ErrBadRequest     = http.StatusBadRequest
	ErrUnauthorized   = http.StatusUnauthorized
	ErrForbidden      = http.StatusForbidden
	ErrNotFound       = http.StatusNotFound
	ErrInternalServer = http.StatusInternalServerError
)

// 定义响应消息映射
var statusMsgMap = map[int]string{
	Success:           "Success",
	ErrBadRequest:     "Bad Request",
	ErrUnauthorized:   "Unauthorized",
	ErrForbidden:      "Forbidden",
	ErrNotFound:       "Not Found",
	ErrInternalServer: "Internal Server Error",
}

// Response 统一响应结构体
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// SendResponse 封装响应的函数
func SendResponse(c *gin.Context, code int, msg string, data interface{}) {
	resp := Response{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	c.JSON(code, resp)
}

// PaginatedResponse 分页响应结构体
type PaginatedResponse struct {
	Response
	Page  int `json:"page"`
	Limit int `json:"limit"`
	Total int `json:"total"`
}

// SendPaginatedResponse 封装分页响应的函数
func SendPaginatedResponse(c *gin.Context, code int, data interface{}, pageStr, limitStr string, total int) {
	page, _ := strconv.Atoi(pageStr)
	limit, _ := strconv.Atoi(limitStr)
	msg, exists := statusMsgMap[code]
	if !exists {
		msg = "Unknown Status"
	}
	resp := PaginatedResponse{
		Response: Response{
			Code: code,
			Msg:  msg,
			Data: data,
		},
		Page:  page,
		Limit: limit,
		Total: total,
	}
	c.JSON(code, resp)
}
